function ismobile() {
    //判断访问终端
    var browser = {
        versions: function () {
            var u = navigator.userAgent, app = navigator.appVersion;
            return {
                trident: u.indexOf('Trident') > -1, //IE内核
                presto: u.indexOf('Presto') > -1, //opera内核
                webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
                gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1,//火狐内核
                mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
                ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
                android: u.indexOf('Android') > -1 || u.indexOf('Adr') > -1, //android终端
                iPhone: u.indexOf('iPhone') > -1, //是否为iPhone或者QQHD浏览器
                iPad: u.indexOf('iPad') > -1, //是否iPad
                webApp: u.indexOf('Safari') == -1, //是否web应该程序，没有头部与底部
                weixin: u.indexOf('MicroMessenger') > -1, //是否微信 （2015-01-22新增）
                qq: u.match(/\sQQ/i) == " qq" //是否QQ
            };
        }(),
        language: (navigator.browserLanguage || navigator.language).toLowerCase()
    };
    if (browser.versions.mobile == true) {
        if (browser.versions.iPhone == true) {
            return '1';
        } else if (browser.versions.android == true) {
            return '0';
        }
    } else {

    }
};
//$(function () {
var useCoupon, $uid, aiCode, token, needAddr;

//getSettlementId();
//seetlementAjax(28, "999287480018", "7538D3B1-DFC3-1658-A6FE-446FEAE4F40A", 110108);
//});
var isMobile = ismobile();

function getSettlementId() {

    if (isMobile == 1) {

        CallSmartListRecommendListModel.jsCallOCWithSendId("Data");

    } else if (isMobile == 0) {

        window.android.getAndroidOrderId("okok")
    }
}

if (isMobile == 0) {

    window.android.getAndroidOrderId("okok")
}
function WebViewDidFinishLoad() {

    var message = {

        "VcWay": "SendId"
    };

    window.webkit.messageHandlers.CallSmartListRecommendListModel.postMessage(message);
}
function receiveiOSVcData(i) {

    var obj = $.parseJSON(i);

    $uid = obj.uid;

    token = obj.TOKEN;

    aiCode = obj.ai_code;

    needAddr = obj.need_addr;

    //console.log(needAddr)

    //alert(needAddr)

    useCoupon = 100;

    seetlementAjax($uid, aiCode, token, needAddr);
}
function receive_android_orderId(k) {


    var obj = $.parseJSON(k);

    $uid = obj.uid;

    token = obj.TOKEN;

    aiCode = obj.ai_code;

    needAddr = obj.need_addr;

    useCoupon = 100;

    //alert($uid + "--" + aiCode + "--" + token + "--" + needAddr)

    seetlementAjax($uid, aiCode, token, needAddr);
}
function seetlementAjax(uid, aiCode, token, needAddr) {

    $.ajax({

        url: url + "users/aiissuelist",

        type: "POST",

        dataType: "json",

        data: {
            "uid": uid,

            "ai_code": aiCode
        },

        //async: "false",

        beforeSend: function (xhr) {

            xhr.setRequestHeader("TOKEN", token);

        },
        success: function (data) {


            //console.log(data)

            if (data.codes == 200) {

                var obj = data.data.list;

                var b = obj.map(function (item, i) {//金额

                    var a = 0;

                    var op = Number(Amount(timeFormat(obj[0].shoot_start_time), timeFormat(obj[0].shoot_end_time), item.current_count, item.warehouse_info.goods_info.shop_price));

                    a += op;

                    item['money'] = op;

                    return a
                });

                var html = template("settlementTpl", data);

                $("#order_body").html(html);

                obj.forEach(function (item, i) {

                    $(".date" + i).html("日期：" + timeFormat(item.shoot_start_time).slice(5) + " ~ " + timeFormat(item.shoot_end_time).slice(5));

                });

                defaultAddress(uid);//获取默认地址

                if (isiphoneX) {

                    $("#order_footer").css("padding-bottom", "0.484rem");

                    $(".moneyDetail").css("padding-bottom", "0.484rem")
                }

                var lists = obj[0];

                //$(".timeStart").html(timeFormat(lists.shoot_start_time));
                //
                //$(".timeEnd").html(timeFormat(lists.shoot_end_time));


                var money = eval(b.join('+')).toFixed(2);

                var c = obj.map(function (item, i) {//押金

                    //var belong_models = item.warehouse_info.goods_info.belong_model;

                    var pp = 0;

                    pp += Number(item.warehouse_info.goods_info.goods_worth * item.current_count);

                    return pp
                });

                var foregift = eval(c.join('+')).toFixed(2);

                $(".cash_pledge").html(foregift);//押金

                $(".proTotal").html(money);//金额

                var coupon = Number($(".couponPrice").html()) || 0;    //优惠券


                var TotalPrice = Number(money) - coupon + Number(foregift);

                //console.log(coupon)

                $(".order_price").html("实付款:￥" + TotalPrice);

                //点击提交订单   判断是否有地址   再判断是否有使用优惠券 调用下单接口

                //var totalMoney = $(".order_price").html().slice(5);

                $(".submit").on("click", function () {

                    var receiveName = $(".address_contacts b").html();

                    var receivePhone = $(".address_phone").html();

                    var address = $(".serviceAddress b").html();

                    //var AddrLength = $(".serviceAddress").attr("data-type");

                    //console.log(AddrLength)

                    if (receivePhone.length > 0) {

                        if (useCoupon == 100) {//未使用优惠券

                            outOrder($uid,

                                lists.theme_type_id,

                                lists.technical_index_id,

                                lists.shoot_start_time,

                                lists.shoot_end_time,

                                TotalPrice,

                                receiveName,

                                receivePhone,

                                address,

                                needAddr,

                                data.data.calendar_id_list,

                                token
                            )
                        } else if (useCoupon == 200) {//使用优惠券

                            var cid = $(".order_coupon").attr("id");//获取优惠券id

                            outOrder($uid,

                                lists.theme_type_id,

                                lists.technical_index_id,

                                lists.shoot_start_time,

                                lists.shoot_end_time,

                                $(".order_price").html().slice(5),

                                receiveName,

                                receivePhone,

                                address,

                                needAddr,

                                data.data.calendar_id_list,

                                token,

                                cid
                            )
                        }
                    } else {

                        if (isMobile == 1) {

                            window.webkit.messageHandlers.CallSmartListRecommendListModel.postMessage({
                                "VcData": "请选择或设置服务地址",
                                "VcWay": "ShowMessage"
                            });

                            //CallSmartListRecommendListModel.jsCalliOSWithShowMessage("请选择或设置服务地址");

                        } else if (isMobile == 0) {

                            window.android.smartOrdertoastMsg("请选择或设置服务地址");
                        }
                    }
                });
                $(".order_address").on("click", function () { //点击添加地址+号，跳转至添加地址页面

                    if (isMobile == 1) {

                        var message = {

                            "VcData": {

                                "contacts": contacts,

                                "iphone": iphone
                            },

                            "VcName": "AddressManager",

                            "VcWay": "AddAddress"
                        };

                        window.webkit.messageHandlers.CallSmartListRecommendListModel.postMessage(message);

                        //
                        //CallSmartListRecommendListModel.jsCalliOSWithAddAddress({
                        //
                        //    "VcData": {
                        //
                        //        "contacts": contacts,
                        //
                        //        "iphone": iphone
                        //
                        //    }, "VcName": "AddressManager"
                        //});
                    } else if (isMobile == 0) {

                        var json = {

                            "address": address4,

                            "province": address2,

                            "city": address3,

                            "contacts": contacts,

                            "iphone": iphone
                        };
                        window.android.jumpToProjectAdress(JSON.stringify(json));
                    }
                });

                $(".order_coupon").on("click",  function () {

                    var typeList = [];//优惠券所属

                    obj.forEach(function (item) {

                        typeList.push(item)

                    });

                    var type = 0;

                    var res = [10];

                    if (typeList.length >= 2) {

                        type = typeList[0];

                        for (var i = 0; i < typeList.length - 1; i++) {

                            if (type == typeList[i + 1]) {

                                res.push(type)
                            }
                            else {

                                res.pop();

                                res = [10];

                                break;
                            }
                        }

                    } else {

                        res.push(typeList[0]);
                    }

                    var json = {

                        "uid": data.data.list[0].uid,

                        "Tprice": money,

                        "type": res
                    };

                    if (isMobile == 1) {

                        var message = {

                            "VcData": json,

                            "VcWay": "OrderCoupons"
                        };

                        window.webkit.messageHandlers.CallSmartListRecommendListModel.postMessage(message);

                        //CallSmartListRecommendListModel.jsCalliOSWithOrderCoupons({"VcData": json});

                    } else if (isMobile == 0) {

                        window.android.showCoupon(JSON.stringify(json));
                    }
                });
                //点击跳转协议
                //$(".xieyi").on("click", function () {
                //
                //    var json = {
                //
                //        "url": "https://viewapi.aipics.cn/view_h5/agreement/lease.html",
                //
                //        "titleName": "用户租赁协议"
                //    };
                //
                //    if (isMobile == 1) {
                //
                //        var message = {
                //
                //            "VcData": json,
                //
                //            "VcName": "PublicWeb",
                //
                //            "VcWay": "PushVCName"
                //        };
                //
                //        window.webkit.messageHandlers.CallSmartListRecommendListModel.postMessage(message);
                //
                //    } else if (isMobile == 0) {
                //
                //        window.android.toRule("...")
                //    }
                //});

            } else {
                if (isMobile == 1) {

                    window.webkit.messageHandlers.CallSmartListRecommendListModel.postMessage({
                        "VcData": "数据获取失败",
                        "VcWay": "ShowMessage"
                    });

                    //CallSmartListRecommendListModel.jsCalliOSWithShowMessage("数据获取失败");

                } else if (isMobile == 0) {

                    window.android.smartOrdertoastMsg("数据获取失败");
                }
            }

        },
        error: function (info) {

            if (isMobile == 1) {

                window.webkit.messageHandlers.CallSmartListRecommendListModel.postMessage({
                    "VcData": "联网失败",
                    "VcWay": "ShowMessage"
                });

                //CallSmartListRecommendListModel.jsCalliOSWithShowMessage("联网失败");

            } else if (isMobile == 0) {

                window.android.smartOrdertoastMsg("联网失败");
            }
        }
    });
}
//格式化时间
function timeFormat(time) {//201712271200

    var y = time.substring(0, 4);

    var m = time.substring(4, 6);

    var d = time.substring(6, 8);

    var h = time.substring(8, 10);

    var s = time.substring(10, 12);

    return (y + "-" + m + "-" + d + " " + h + ":" + s)

}
//订单收货地址
var address1 = "", address2 = "", address3 = "", address4 = "", contacts = "", iphone = "", iphone1 = "", contacts1 = "";

//接收ios和安卓的内容
function receiveiOSAddAddress(a) {
    var result = JSON.parse(a);

    address1 = $(".serviceAddress b ").html(result['shipping_address']);

    //address2=a.addressDetails;

    //address3=a.addressTitle;

    iphone = result.link_mobile;

    contacts = result.link_man;

    contacts1 = $(".address_contacts b ").html(result['link_man']);

    iphone1 = $(".address_phone").html(result['link_mobile']);

    $(".address").css("margin-left", "0");

}
function receive_android_addAddress(k) {
    //字符串转json
    var result = JSON.parse(k);

    address1 = $(".serviceAddress b").html(result.province + result.city + result.district + result.address);

    address2 = result.province;

    address3 = result.city;

    address4 = result.address;

    iphone = result.iphone;

    contacts = result.contacts;

    contacts1 = $(".address_contacts b").html(result.contacts);

    iphone1 = $(".address_phone").html(result.iphone);

    $(".address").css("margin-left", "0");
}
//点击订单中的优惠券，接收ios的参数【用户id，优惠券id，优惠券价格】

function receiveiOSOrderCoupon(a) {
    var obj = $.parseJSON(a);

    if (obj) {
        useCoupon = 200;

        $(".couponPrice").html(obj.face);

        $(".order_coupon").attr("id", obj.id);

        var money = $(".proTotal").html();//商品价格

        var sendTotal = Number($(".sendTotal").html());//运费

        var cash_pledge = Number($(".cash_pledge").html());//押金

        // var insurance = parseInt($(".insurance").html());// 保险

        var couponPrice = Number(obj.face) || 0; //优惠券

        $(".counpMoney").html(couponPrice);//优惠金额

        $(".order_price").html("实付款:￥" + (Number(money) + sendTotal + cash_pledge - couponPrice));//总价

    } else {
        useCoupon = 100;

        $(".couponPrice").html("请选择");
        // alert(useCoupon)
    }

}
//点击订单中的优惠券，接收android的信息
function receive_android_orderCoupon(k) {
    var obj = $.parseJSON(k);
    if (obj) {

        useCoupon = 200;

        $(".couponPrice").html(obj.face);

        $(".order_coupon").attr("id", obj.cid);

        var money = $(".proTotal").html();//商品价格

        var sendTotal = Number($(".sendTotal").html());//运费

        var cash_pledge = Number($(".cash_pledge").html());//押金

        // var insurance = parseInt($(".insurance").html());// 保险

        var couponPrice = Number(obj.face) || 0; //优惠券

        $(".counpMoney").html(couponPrice);//优惠金额

        $(".order_price").html("实付款:￥" + (Number(money) + sendTotal + cash_pledge - couponPrice));//总价

    } else {
        useCoupon = 100;

        $(".couponPrice").html("请选择");
    }

}
//计算价格
function Amount(start_time, end_time, number, price) {

    var diffSecond = (Date.parse(new Date(end_time.replace(/-/g, "/"))) - Date.parse(new Date(start_time.replace(/-/g, "/")))) / 1000;

    var diffHour = diffSecond / 3600;

    var diffDay = Math.floor(diffSecond / (24 * 3600));

    var remainderMoney = 0;

    if (diffHour > 24) {

        remainderHour = Math.ceil(diffHour % 24);

        if (remainderHour > 8) {

            diffDay += 1;

        } else {

            remainderMoney = (price / 8) * remainderHour;
        }
        return Number((diffDay * price + remainderMoney) * number).toFixed(2);

    } else {

        return Number(price * number).toFixed(2);
    }

}
//智能出单提交(提交出单)
function outOrder(uid, typeId, technicalId, startTime, endTime, totalMoney, name, mobile, addr, needAddr, warehouseIds, token, cid) {
    //alert(name+"--"+addr+"--"+needAddr)

    $.ajax({

        type: "POST",

        url: url + "users/aiprofessionalsubmit",

        dataType: "json",

        //async: "false",

        //timeout: 30000, //超时时间：30秒

        beforeSend: function (xhr) {

            xhr.setRequestHeader("TOKEN", token);
        },
        data: {
            "uid": uid,

            "source_theme_type_id": typeId,

            "source_technical_index_id": technicalId,

            "shoot_start_time": startTime,

            "shoot_end_time": endTime,

            "total_money": totalMoney,

            "receive_user_name": name,

            "receive_user_mobile": mobile,

            "receive_user_addr": addr,

            "need_addr_id": needAddr,

            "warehouse_ids": warehouseIds,

            "use_coupon": useCoupon,

            "coupon_id": cid
        },

        success: function (data) {

            if (data.codes == "200") {

                var result = data.data.order_code;

                if (isMobile == 1) {

                    var message = {

                        "VcData": {"order_code": result},

                        "VcName": "ListPay",

                        "VcWay": "PushVCName"
                    };

                    window.webkit.messageHandlers.CallSmartListRecommendListModel.postMessage(message);

                    //CallSmartListRecommendListModel.jsCalliOSWithPushVCName({
                    //
                    //    "VcData": {"order_code": result},
                    //
                    //    "VcName": "ListPay"
                    //
                    //});
                } else if (isMobile == 0) {

                    window.android.jumptoOrderActivity(result);

                }
            } else if (data.codes != "200" && data.codes) {

                if (isMobile == 1) {

                    window.webkit.messageHandlers.CallSmartListRecommendListModel.postMessage({
                        "VcData": data.msg,
                        "VcWay": "ShowMessage"
                    });

                    //CallSmartListRecommendListModel.jsCalliOSWithShowMessage(data.msg);

                } else if (isMobile == 0) {

                    window.android.smartOrdertoastMsg(data.msg);

                }
            } else if (data.codes == null) {

                if (isMobile == 1) {

                    window.webkit.messageHandlers.CallSmartListRecommendListModel.postMessage({
                        "VcData": "系统繁忙，请稍后重试",
                        "VcWay": "ShowMessage"
                    });

                    //CallSmartListRecommendListModel.jsCalliOSWithShowMessage("系统繁忙，请稍后重试");

                } else if (isMobile == 0) {

                    window.android.smartOrdertoastMsg("系统繁忙，请稍后重试");
                }
            }
        },
        error: function (info) {

            if (isMobile == 1) {

                window.webkit.messageHandlers.CallSmartListRecommendListModel.postMessage({
                    "VcData": "联网失败",
                    "VcWay": "ShowMessage"
                });

                //CallSmartListRecommendListModel.jsCalliOSWithShowMessage("联网失败");

            } else if (isMobile == 0) {

                window.android.smartOrdertoastMsg("联网失败");
            }
        }

    });
}
function defaultAddress(uid) {
    $.ajax({

        url: url + "users/fourModel",

        type: "POST",

        dataType: "json",

        data: {
            "url": "address/lists",

            "uid": uid,

            "addr_type": 1
        },

        success: function (data) {

            //console.log(data)

            if (data.codes == 200) {

                var list = data.data.list[0];

                $(".address_contacts b").html(list.link_man);

                $(".address_phone").html(list.link_mobile);

                $(".serviceAddress b").html(list.shipping_address);

                $(".address").css("margin-left", "0");

                //$(".order_address").attr("data-type", "100");

                //$(".address .defultaddr").css("display", "block");

            }
        },
        error: function (info) {

            if (isMobile == 1) {

                window.webkit.messageHandlers.CallSmartListRecommendListModel.postMessage({
                    "VcData": "联网失败",
                    "VcWay": "ShowMessage"
                });

                //CallSmartListRecommendListModel.jsCalliOSWithShowMessage("联网失败");

            } else if (isMobile == 0) {

                window.android.smartOrdertoastMsg("联网失败");
            }
        }
    });
}
